﻿using MaterialDesignColors;
using MaterialDesignThemes.Wpf;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Prism.Commands;
using Prism.Mvvm;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Windows.Controls.Primitives;
using System.Xml.Linq;

namespace Module.MDViews.ViewModels
{
    public class PaletteSelectorViewModel : BindableBase
    {
        public PaletteSelectorViewModel()
        {
            ToggleStyleCommand = new DelegateCommand<object>(ApplyStyle);
            ApplyPrimaryCommand = new DelegateCommand<Swatch>(ApplyPrimary);
            ApplyAccentCommand = new DelegateCommand<Swatch>(ApplyAccent);

            Swatches = new SwatchesProvider().Swatches;
            //Swatch swatch = Swatches.Where(o => o.Name == "yellow").FirstOrDefault();

            PaletteHelper paletteHelper = new PaletteHelper();
            Theme theme = paletteHelper.GetTheme();
            //theme.SetPrimaryColor(swatch.ExemplarHue.Color);
            //if (swatch.AccentExemplarHue is Hue accentHue)
            //{
            //    theme.SetSecondaryColor(accentHue.Color);
            //}
            //paletteHelper.SetTheme(theme);
            IsDarkTheme = theme.GetBaseTheme() == BaseTheme.Dark;
        }

        private bool _isDarkTheme;

        public bool IsDarkTheme
        {
            get => _isDarkTheme;
            set
            {
                if (_isDarkTheme != value)
                {
                    //_isDarkTheme = value;
                    SetProperty(ref _isDarkTheme, value);
                    //PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(IsDarkTheme)));
                    ApplyBase(value);
                }
            }
        }

        public DelegateCommand<object> ToggleStyleCommand { get; set; }

        private void ApplyStyle(object obj)
        {
            //bool alternate = Convert.ToBoolean(obj);
            //var resourceDictionary = new ResourceDictionary
            //{
            //    Source = new Uri(@"pack://application:,,,/Dragablz;component/Themes/materialdesign.xaml")
            //};

            //var styleKey = alternate ? "MaterialDesignAlternateTabablzControlStyle" : "MaterialDesignTabablzControlStyle";
            //var style = (Style)resourceDictionary[styleKey];

            //foreach (var tabablzControl in Dragablz.TabablzControl.GetLoadedInstances())
            //{
            //    tabablzControl.Style = style;
            //}
        }

        private static void ApplyBase(bool isDark)
        {
            if (isDark)
            {
                Write("Theme", "true");
            }
            else
            {
                Write("Theme", "false");
            }
            ModifyTheme(theme => theme.SetBaseTheme(isDark ? BaseTheme.Dark : BaseTheme.Light));
        }

        private static void ModifyTheme(Action<Theme> modificationAction)
        {
            PaletteHelper paletteHelper = new PaletteHelper();
            Theme theme = paletteHelper.GetTheme();

            modificationAction?.Invoke(theme);

            paletteHelper.SetTheme(theme);
        }

        #region change theme

        public IEnumerable<Swatch> Swatches { get; }

        public DelegateCommand<Swatch> ApplyPrimaryCommand { get; }// = new AnotherCommandImplementation(o => ApplyPrimary((Swatch)o!));

        public DelegateCommand<Swatch> ApplyAccentCommand { get; }// = new AnotherCommandImplementation(o => ApplyAccent((Swatch)o!));

        private static void ApplyPrimary(Swatch swatch)
        {
            Write("SwatchName", swatch.Name);
            Write("PrimaryColor", swatch.ExemplarHue.Color.ToString());
            Write("AccentColor", swatch.SecondaryExemplarHue.Color.ToString());
            ModifyTheme(theme => theme.SetPrimaryColor(swatch.ExemplarHue.Color));
        }

        private static void ApplyAccent(Swatch swatch)
        {
            if (swatch.SecondaryExemplarHue is Hue accentHue)
            {
                ModifyTheme(theme => theme.SetSecondaryColor(accentHue.Color));
            }
        }

        #endregion change theme

        public static void Write(string key, string value)
        {
            string folder = Directory.GetCurrentDirectory(); //获取应用程序的当前工作目录。
            string filePath = folder + "\\appsettings.json";
            JObject jsonObject;
            using (StreamReader file = new StreamReader(filePath))
            using (JsonTextReader reader = new JsonTextReader(file))
            {
                jsonObject = (JObject)JToken.ReadFrom(reader);
                //jsonObject["appSettings"]["Key"] = "asdasdasdasd";
                jsonObject["MdTheme"][key] = value;
                file.Close();
                reader.Close();
            }

            using (var writer = new StreamWriter(filePath))
            using (JsonTextWriter jsonwriter = new JsonTextWriter(writer))
            {
                jsonObject.WriteTo(jsonwriter);
            }
        }
    }
}